#include "threadPool.h"
typedef struct train_s
{
    int length;
    char data[1000];
}train_t;
int do_puts(char* buf,int netfd)
{
    char filename[1024];
        //file_position += strlen(filename)+1;//这里是为了处理可能会一次puts多个文件的情况，如puts file1 file2
       train_t train;
       train.length = strlen(buf)+1;
       memcpy(train.data,buf,train.length);
       if(downloadFromServer(netfd,filename) == 0)
        {
            printf("download success!\n");
        }
        else
        {
            printf("download failed!\n");
        }
}
int downloadFromServer(int fdToDownloadfile,char* filename)
{
    int filefd = open(filename,O_RDWR|O_CREAT,0666);
    ERROR_CHECK(filefd,-1,"open");
    char* writebuf = (char*)malloc(4096);//?后面可以申请大一些
    bzero(writebuf,4096);

    //这里用小火车协议，先发长度
    int lengthTowrite;
    while(1)
    {
        recv(fdToDownloadfile,&lengthTowrite,sizeof(int),0);
        if(lengthTowrite == 0)//说明没读到什么东西，就break掉
        {
            break;
        }
        //如果length不为0，就把从网络sockfd中的内容读到writebuf缓冲区
        recv(fdToDownloadfile,writebuf,lengthTowrite,0);
        //然后再把writebuf缓冲区的内容写到上面open的文件中，通过filefd
        write(filefd,writebuf,lengthTowrite);
    }
    close(filefd);
    return 0;
}
